package com.itcam.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.itcam.apis.wemedia.IWemediaClient;
import com.itcam.article.mapper.ApArticleMapper;
import com.itcam.article.service.HotArticleService;
import com.itcam.common.constants.ArticleConstants;
import com.itcam.common.redis.CacheService;
import com.itcam.model.article.pojos.ApArticle;
import com.itcam.model.article.vos.HotArticleVo;
import com.itcam.model.common.dtos.ResponseResult;
import com.itcam.model.wemedia.pojos.WmChannel;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author : Cammy.Wu
 * Description : 
 */

@Service
public class HotArticleServiceImpl implements HotArticleService {

    @Autowired
    private ApArticleMapper apArticleMapper;


    /**
     * 计算热点文章
     */
    @Override
    public void computeHotArticle() {
        // 1.查询前五天的文章数据
        Date dateParam = DateTime.now().minusDays(5).toDate();
        List<ApArticle> apArticleList = apArticleMapper.findArticleListByLast5days(dateParam);
        // 2.计算文章的分值
        List<HotArticleVo> hotArticleVoList = this.computeHotArticle(apArticleList);
        //3.为每个频道缓存30条分值较高的文章
        this.cacheTagToRedis(hotArticleVoList);
    }

    // _____________________________________________________________________________________________________________________

    /**
     * 计算文章分值
     * @param apArticleList
     * @return
     */
    private List<HotArticleVo> computeHotArticle(List<ApArticle> apArticleList) {
        // 创建一个新的热点文章列表
        List<HotArticleVo> hotArticleVoList = new ArrayList<>();
        // 如果文章列表不为空
        if (apArticleList != null && apArticleList.size() > 0) {
            // 遍历文章列表
            for (ApArticle apArticle : apArticleList) {
                // 创建一个新的热点文章对象
                HotArticleVo hot = new HotArticleVo();
                // 将文章对象的属性复制到热点文章对象中
                BeanUtils.copyProperties(apArticle, hot);
                // 计算文章的得分
                Integer score = computeScore(apArticle);
                // 设置热点文章的得分
                hot.setScore(score);
                // 将热点文章添加到列表中
                hotArticleVoList.add(hot);
            }
        }
        // 返回热点文章列表
        return hotArticleVoList;

    }

    /**
     * 计算文章的具体分值
     * @param apArticle
     * @return
     */
    private Integer computeScore(ApArticle apArticle) {
        // 1.计算文章分值
        Integer score = 0;
        // 1.1 阅读文章权重
        if (apArticle.getViews() != null) {
            score += apArticle.getViews();
        }
        // 1.2 点赞文章权重
        if (apArticle.getLikes() != null) {
            score += apArticle.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        // 1.3 评论文章权重
        if (apArticle.getComment() != null) {
            score += apArticle.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        // 1.4 收藏文章权重
        if (apArticle.getCollection() != null) {
            score += apArticle.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }
        return score;
    }

    @Autowired
    private IWemediaClient wemediaClient;

    /**
     * 为每个频道缓存30条分值较高的文章
     * @param hotArticleVoList
     */
    private void cacheTagToRedis(List<HotArticleVo> hotArticleVoList) {
        // 为每个频道缓存30条分值较高的文章
        ResponseResult responseResult = wemediaClient.getChannels();
        if (responseResult.getCode().equals(200)) {
            String channelJson = JSON.toJSONString(responseResult.getData());
            List<WmChannel> wmChannels = JSON.parseArray(channelJson, WmChannel.class);
            // 检索出每个频道的文章
            if (wmChannels != null && !wmChannels.isEmpty()) {
                for (WmChannel wmChannel : wmChannels) {
                    List<HotArticleVo> hotArticleVos = hotArticleVoList.stream()
                            .filter(x -> x.getChannelId().equals(wmChannel.getId()))
                            .collect(Collectors.toList());
                    // 给文章进行排序，取30条分值较高的文章存入redis  key：频道id   value：30条分值较高的文章
                    this.sortAndCache(hotArticleVos, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + wmChannel.getId());
                }
            }
        }
        //设置推荐数据
        //给文章进行排序，取30条分值较高的文章存入redis  key：频道id   value：30条分值较高的文章
        sortAndCache(hotArticleVoList, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG);

    }

    @Autowired
    private CacheService cacheService;

    /**
     * 排序并且缓存数据
     * @param hotArticleVoList
     * @param key
     */
    private void sortAndCache(List<HotArticleVo> hotArticleVoList, String key) {
        // 使用流API对hotArticleVoList进行排序，按照HotArticleVo的score属性降序排列
        hotArticleVoList = hotArticleVoList.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());
        // 如果排序后的列表长度大于30，则截取前30条记录
        if (hotArticleVoList.size() > 30) {
            hotArticleVoList = hotArticleVoList.subList(0, 30);
        }
        // 将截取后的列表转换为JSON字符串，并将其缓存到Redis中，key为传入的参数key
        cacheService.set(key, JSON.toJSONString(hotArticleVoList));

    }
}
